#!/bin/bash

test_install()
{
    local rpmPath=$1
    cd ${rpmPath}
    if [ -z "$(ls | grep -E '.rpm$')" ];then
        return 1
    fi
    yum install -y *.rpm &> install_log.txt
    return $?
}

test_uninstall()
{
    local rpmPath=$1
    local res=0
    cd ${rpmPath}
    if [ -z "$(ls | grep -E '.rpm$')" ];then
        return 1
    fi
    for rpmfile in $(ls *.rpm)
    do
        rpm -e --nodeps ${rpmfile%'.rpm'*} &> uninstall_log.txt
        let "res = ${res} + $?"
    done
    return ${res}
}

setup()
{
    [ -f ${TONE_BM_RUN_DIR}/.shrc ] && . ${TONE_BM_RUN_DIR}/.shrc
    . ${TONE_SUITE_DIR}/jdk-rpm-install-test/common.sh
}


run()
{
    set -x
    local testPath=${TONE_BM_RUN_DIR}/rpm2install
    [ -d ${testPath} ] || die "Cannot find testPath ${testPath}"
    test_install ${testPath}
    if [ $? -eq 0 ];then
        echo "test-install: Pass" >> ${TONE_BM_RUN_DIR}/test-result.log
    else
        echo "test-install: Fail" >> ${TONE_BM_RUN_DIR}/test-result.log
    fi

    if [ -n "$(which java | grep 'no java in')" ];then
        javaPath=$(find /usr/lib/jvm -iname java | grep -w 'bin/java' | head -n 1)
        [ -n ${javaPath} ] || die "Cannot find java"
        ${javaPath} -version
    else
        java -version
    fi
    if [ $? -eq 0 ];then
        echo "test-jdk: Pass" >> ${TONE_BM_RUN_DIR}/test-result.log
    else
        echo "test-jdk: Fail" >> ${TONE_BM_RUN_DIR}/test-result.log
    fi

    test_uninstall ${testPath}
    if [ $? -eq 0 ];then
        echo "test-uninstall: Pass" >> ${TONE_BM_RUN_DIR}/test-result.log
    else
        echo "test-uninstall: Fail" >> ${TONE_BM_RUN_DIR}/test-result.log
    fi
}

parse()
{
    cat ${TONE_BM_RUN_DIR}/test-result.log
    if [ -n "$(grep 'Fail' ${TONE_BM_RUN_DIR}/test-result.log)" ];then
        return -1
    fi
}
